package com.mall.module.system.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.common.exception.BusinessException;
import com.mall.common.result.ResultCode;
import com.mall.module.system.domain.entity.SysDict;
import com.mall.module.system.mapper.SysDictMapper;
import com.mall.module.system.service.SysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 系统字典服务实现类
 */
@Service
public class SysDictServiceImpl implements SysDictService {

    @Autowired
    private SysDictMapper dictMapper;

    @Override
    public PageInfo<SysDict> listDictPage(Integer pageNum, Integer pageSize, String dictType, String dictKey, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysDict> list = dictMapper.selectDictList(dictType, dictKey, status);
        return new PageInfo<>(list);
    }

    @Override
    public List<SysDict> listDictByType(String dictType) {
        return dictMapper.selectDictByType(dictType);
    }

    @Override
    public SysDict getDictByTypeAndKey(String dictType, String dictKey) {
        return dictMapper.selectDictByTypeAndKey(dictType, dictKey);
    }

    @Override
    public SysDict getDictById(Long id) {
        return dictMapper.selectDictById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addDict(SysDict dict) {
        // 检查是否已存在相同类型和键的字典
        SysDict existDict = dictMapper.selectDictByTypeAndKey(dict.getDictType(), dict.getDictKey());
        if (existDict != null) {
            throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "相同类型和键的字典已存在");
        }
        
        return dictMapper.insertDict(dict) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDict(SysDict dict) {
        // 检查是否存在
        SysDict existDict = dictMapper.selectDictById(dict.getId());
        if (existDict == null) {
            throw new BusinessException(ResultCode.DATA_NOT_EXISTED, "字典不存在");
        }
        
        // 检查是否存在相同类型和键的其他字典
        SysDict sameDict = dictMapper.selectDictByTypeAndKey(dict.getDictType(), dict.getDictKey());
        if (sameDict != null && !sameDict.getId().equals(dict.getId())) {
            throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "相同类型和键的字典已存在");
        }
        
        return dictMapper.updateDict(dict) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDict(Long id) {
        return dictMapper.deleteDictById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteDictByIds(List<Long> ids) {
        return dictMapper.deleteDictByIds(ids) > 0;
    }
} 